package dao;

import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import pojo.Cart;

public class CartDaoa {
	private ComboPooledDataSource ds=new ComboPooledDataSource();
	private QueryRunner qr=new QueryRunner(ds);
	//向购物车中添加数据
	public int addCart(Cart c) {
		int flag=0;
		String sql="insert into cart(c_name,p_id,quantity,p_price,amount,p_image,p_name,orderId)"
				+ "values(?,?,?,?,?,?,?,?)";
		try {
			flag=qr.update(sql,c.getC_name(),c.getP_id(),c.getQuantity(),c.getP_price(),c.getAmount(),c.getP_image(),c.getP_name(),UUID.randomUUID()+"");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
	//显示购物车内容
	public List<Cart> showCart(int currentPage,int pageSize,String c_name){
		List<Cart> list=null;
		String sql="select * from cart where c_name=? limit ?,?";
		try {
			list=qr.query(sql, new BeanListHandler<Cart>(Cart.class),c_name,(currentPage-1)*pageSize+1,pageSize);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(list.size());
		return list;
	}
	//获取总条数
	public int getCount() {
		int count=0;
		String sql="select count(*) from cart";
		try {
			long i = (long) qr.query(sql, new ScalarHandler());
			count = (int)i;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return count;
	}
	//获取一个数据
	public Cart getOne(String p_id) {
		String sql="select * from cart where p_id=?";
		Cart t = null;
		try {
			t=qr.query(sql, new BeanHandler<Cart>(Cart.class),p_id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}
	//修改数量
	public int updateNumber(Cart t) {
		int flag = 0;
		Cart c = this.getOne(t.getP_id());
		String sql = "update cart set quantity=?,amount=? where p_id=?";
		try {
			flag = qr.update(sql,c.getQuantity()+1,c.getP_price()*(c.getQuantity()+1),t.getP_id());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
}
